package com.tiza.test.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

public class DBUtils {

    private static Logger LOG = LoggerFactory.getLogger(DBUtils.class);

    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static {

        Configuration conf = Configuration.getInstance();
        conf.load("app.properties");

        driverClass = conf.getConfig("db.driver");
        url = conf.getConfig("db.url");
        username = conf.getConfig("db.username");
        password = conf.getConfig("db.password");

        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            LOG.error(e.getMessage(), e);
            System.exit(-1);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static void close(Connection conn) {
        if(conn == null) return;
        try {
            conn.close();
        } catch (SQLException e) {
            LOG.warn("Connection close failed: " + e.getMessage());
        }
    }

    public static void close(Connection conn, Statement stmt) {
        if(stmt == null) return;
        try {
            stmt.close();
        } catch (SQLException e) {
            LOG.warn("Statement close failed: " + e.getMessage());
        }
        close(conn);
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if(rs == null) return;
        try {
            rs.close();
        } catch (SQLException e) {
            LOG.warn("ResultSet close failed: " + e.getMessage());
        }
        close(conn, stmt);
    }

}
